package com.fmatos.amazingwallpapers.image.network;

import java.net.URLConnection;

import org.joda.time.DateTime;

import android.util.Log;

public class CloudPing  {

	private static final String TAG = CloudPing.class.getSimpleName();
	private static CloudHelper cloudHelper = new CloudHelper();
	
	private static DateTime lastPing = new DateTime(0);
	private static boolean lastResponse = false;
	
	// TODO: 1- check if time is enough for turning heroku on
	// TODO: 2- if server is down try checking google.com for network connectivity confirmation
	
	/**
	 * Pings server to make sure it's up and running before making other requests. This method may take a long time to execute.
	 * Caches response for at most 2 minutes, and tries pinging server 4 times before quitting (each time may wait up to 5 seconds more or less
	 * @return whether server is dead or alive
	 */
	public synchronized static boolean isServerAlive() {
		DateTime start =  new DateTime();
		
		// ping every 2 minutes at most
		if ( lastResponse && lastPing.plusMinutes(2).isAfter(start.getMillis())) {
			Log.i(TAG,"Ping will answer precached response");
			return lastResponse;
		}
		
		lastPing = start;
		Log.i(TAG,"Starting to ping server at " + start.getMillisOfDay());
		
		int retry = 5;
		lastResponse = false;
		while ( retry > 0 && ! lastResponse  ) {
			retry--;
			lastResponse = pingServer();
		}

		
		DateTime finish = new DateTime();
		long time = finish.getMillis() - start.getMillis();

		Log.i(TAG,"Ping took " + time + " ms");
		return lastResponse;
	}
	
	
	private static boolean pingServer() {

		boolean isAlive = false;
		
		URLConnection connection = cloudHelper.connectToUrl(CloudClient.HEROKU_BASE_URL +  CloudClient.HEROKU_URL_PING );

		StringBuilder response = cloudHelper.getStringFromConnection(connection);
		Log.i(TAG,"Ping responded " + response);

		if ( response!= null ) {
			isAlive = "Hello World!".equals(response.toString());
		}

		return isAlive;
	}
}
